{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**欢迎关注Pyhton金融量化**  \n",
    "\n",
    "此文件仅供金融量化知识星球圈友学习参考，请勿外传 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:32:58.429109Z",
     "start_time": "2019-08-05T14:32:56.210852Z"
    }
   },
   "outputs": [],
   "source": [
    "#引入可能用到的包\n",
    "import pandas as pd  \n",
    "import talib as ta\n",
    "import numpy as np\n",
    "from scipy import stats\n",
    "import tushare as ts \n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline   \n",
    "\n",
    "#正常显示画图时出现的中文和负号\n",
    "from pylab import mpl\n",
    "mpl.rcParams['font.sans-serif']=['SimHei']\n",
    "mpl.rcParams['axes.unicode_minus']=False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:33:00.311702Z",
     "start_time": "2019-08-05T14:33:00.302727Z"
    }
   },
   "outputs": [],
   "source": [
    "#获取股票代码\n",
    "index={'上证综指': '000001.SH',\n",
    "        '深证成指': '399001.SZ',\n",
    "        '沪深300': '000300.SH',\n",
    "        '创业板指': '399006.SZ',\n",
    "        '上证50': '000016.SH',\n",
    "        '中证500': '000905.SH',\n",
    "        '中小板指': '399005.SZ',\n",
    "        '上证180': '000010.SH'}\n",
    "\n",
    "#获取当前交易的股票代码和名称\n",
    "def get_code():\n",
    "    df = pro.stock_basic(exchange='', list_status='L')\n",
    "    codes=df.ts_code.values\n",
    "    names=df.name.values\n",
    "    stock=dict(zip(names,codes))\n",
    "    #合并指数和个股成一个字典\n",
    "    stocks=dict(stock,**index)\n",
    "    return stocks    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:33:01.192249Z",
     "start_time": "2019-08-05T14:33:01.120443Z"
    }
   },
   "outputs": [],
   "source": [
    "# 获取交易数据\n",
    "#使用之前先输入token，可以从个人主页上复制出来，每次调用数据需要先运行该命令\n",
    "token='e0eeb08befd1f07516df2cbf9cbd58663f77fd72f92a04f290291c9d'\n",
    "ts.set_token(token)\n",
    "pro=ts.pro_api()\n",
    "def get_daily_data(stock,start='',end=''):\n",
    "    code=get_code()[stock]\n",
    "    #如果代码在字典index里，则取的是指数数据\n",
    "    if code in index.values():\n",
    "        df=pro.index_daily(ts_code=code,start_date=start, end_date=end)\n",
    "    #否则取的是个股数据\n",
    "    else:\n",
    "        df=pro.daily(ts_code=code, start_date=start, end_date=end)\n",
    "    #将交易日期设置为索引值\n",
    "    df.index=pd.to_datetime(df.trade_date)\n",
    "    df=df.sort_index()\n",
    "    df['date']=pd.to_datetime(df.trade_date)\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:55:24.578761Z",
     "start_time": "2019-08-05T14:55:24.567792Z"
    }
   },
   "outputs": [],
   "source": [
    "# 交易策略，简单均线策略,输出每天的仓位\n",
    "def strategy_ma(stock_data, short=5, long=20):\n",
    "    \"\"\"\n",
    "    :param stock_data: 股票数据集\n",
    "    :param short: 较短的窗口期\n",
    "    :param long: 较长的窗口期\n",
    "    :return: 当天收盘时持有该股票的仓位。\n",
    "\n",
    "    最简单的均线策略。当天收盘后，短期均线上穿长期均线的时候，在第二天开盘买入。\n",
    "     当短期均线下穿长期均线的时候，在第二天开盘卖出。每次都是全仓买卖.\n",
    "\n",
    "    \"\"\"\n",
    "    # 计算短期和长期的移动平均线\n",
    "    stock_data['ma_short'] = ta.MA(stock_data['close'], timeperiod=short)\n",
    "    stock_data['ma_long'] = ta.MA(stock_data['close'], timeperiod=long)\n",
    "\n",
    "    # 出现买入信号而且第二天开盘没有涨停\n",
    "    stock_data.loc[(stock_data['ma_short'].shift(1) > stock_data['ma_long'].shift(1)) &\n",
    "                  (stock_data['open'] < stock_data['close'].shift(1) * 1.097), 'position'] = 1\n",
    "    # 出现卖出信号而且第二天开盘没有跌停\n",
    "    stock_data.loc[(stock_data['ma_short'].shift(1) < stock_data['ma_long'].shift(1)) &\n",
    "                  (stock_data['open'] > stock_data['close'].shift(1) * 0.903), 'position'] = 0\n",
    "\n",
    "    stock_data['position'].fillna(method='ffill', inplace=True)\n",
    "    stock_data['position'].fillna(0, inplace=True)\n",
    "    stock_data['ret']=stock_data['pct_chg']/100\n",
    "    return stock_data[['ts_code', 'date', 'open', 'close', 'ret', 'position']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:55:25.117632Z",
     "start_time": "2019-08-05T14:55:25.108656Z"
    }
   },
   "outputs": [],
   "source": [
    "# 根据每日仓位计算总资产的日收益率\n",
    "def position(df, slippage=1.0 / 1000, commision_rate=2.0 / 10000):\n",
    "    \"\"\"\n",
    "    :param df: 股票账户数据集\n",
    "    :param slippage: 买卖滑点 默认为1.0 / 1000\n",
    "    :param commision_rate: 手续费 默认为2.0 / 10000\n",
    "    :return: 返回账户资产的日收益率和日累计收益率的数据集\n",
    "    \"\"\"\n",
    "    df.loc[df.index[0], 'capital_rtn'] = 0\n",
    "    # 当加仓时,计算当天资金曲线涨幅capital_rtn.capital_rtn = 昨天的position在今天涨幅\n",
    "    #+ #今天开盘新买入的position在今天的涨幅(扣除手续费)\n",
    "    df.loc[df['position'] > df['position'].shift(1), 'capital_rtn'] = (df['close'] / df['open'] - 1) * (\n",
    "        1 - slippage - commision_rate) * (df['position'] - df['position'].shift(1)) + df['ret'] * df[\n",
    "        'position'].shift(1)\n",
    "    # 当减仓时,计算当天资金曲线涨幅capital_rtn.capital_rtn = 今天开盘卖出的positipn\n",
    "    #在今天的涨幅(扣除手续费) + #还剩的position在今天的涨幅\n",
    "    df.loc[df['position'] < df['position'].shift(1), 'capital_rtn'] = (df['open'] / df['close'].shift(1) \n",
    "     - 1) * (1 - slippage - commision_rate) * (df['position'].shift(1) - df['position']) + df['ret'] * df['position']\n",
    "    # 当仓位不变时,当天的capital_rtn是当天的change * position\n",
    "    df.loc[df['position'] == df['position'].shift(1), 'capital_rtn'] = df['ret'] * df['position']\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:55:25.992771Z",
     "start_time": "2019-08-05T14:55:25.971825Z"
    }
   },
   "outputs": [],
   "source": [
    "# 计算最近250天的股票,策略累计涨跌幅.以及每年（月，周）股票和策略收益\n",
    "def period_return(stock_data, days=250, if_print=False):\n",
    "    \"\"\"\n",
    "    :param stock_data: 包含日期、股票涨跌幅和总资产涨跌幅的数据集\n",
    "    :param days: 最近250天\n",
    "    :return: 输出最近250天的股票和策略累计涨跌幅以及每年的股票收益和策略收益\n",
    "    \"\"\"\n",
    "    df = stock_data.loc[:,['ts_code','trade_date', 'ret', 'capital_rtn']]\n",
    "\n",
    "    # 计算每一年(月,周)股票,资金曲线的收益\n",
    "    year_rtn = df.loc[:,['ret', 'capital_rtn']].resample('A').apply(lambda x: (x + 1.0).prod() - 1.0)\n",
    "    month_rtn = df.loc[:,['ret', 'capital_rtn']].resample('M').apply(lambda x: (x + 1.0).prod() - 1.0)\n",
    "    week_rtn = df.loc[:,['ret', 'capital_rtn']].resample('W').apply(lambda x: (x + 1.0).prod() - 1.0)\n",
    "\n",
    "    year_rtn.dropna(inplace=True)\n",
    "    month_rtn.dropna(inplace=True)\n",
    "    week_rtn.dropna(inplace=True)\n",
    "\n",
    "    # 计算策略的年（月，周）胜率\n",
    "    yearly_win_rate = len(year_rtn[year_rtn['capital_rtn'] > 0]) / len(year_rtn[year_rtn['capital_rtn'] != 0])\n",
    "    monthly_win_rate = len(month_rtn[month_rtn['capital_rtn'] > 0]) / len(month_rtn[month_rtn['capital_rtn'] != 0])\n",
    "    weekly_win_rate = len(week_rtn[week_rtn['capital_rtn'] > 0]) / len(week_rtn[week_rtn['capital_rtn'] != 0])\n",
    "\n",
    "    # 计算股票的年（月，周）胜率\n",
    "    yearly_win_rates = len(year_rtn[year_rtn['ret'] > 0]) / len(year_rtn[year_rtn['ret'] != 0])\n",
    "    monthly_win_rates = len(month_rtn[month_rtn['ret'] > 0]) / len(month_rtn[month_rtn['ret'] != 0])\n",
    "    weekly_win_rates = len(week_rtn[week_rtn['ret'] > 0]) / len(week_rtn[week_rtn['ret'] != 0])\n",
    "\n",
    "    # 计算最近days的累计涨幅\n",
    "    df = df.iloc[-days:]\n",
    "    recent_rtn_line = df.loc[:,['trade_date']]\n",
    "    recent_rtn_line['stock_rtn_line'] = (df['ret'] + 1).cumprod() - 1\n",
    "    recent_rtn_line['strategy_rtn_line'] = (df['capital_rtn'] + 1).cumprod() - 1\n",
    "    recent_rtn_line.reset_index(drop=True, inplace=True)\n",
    "\n",
    "    # 输出\n",
    "    if if_print:\n",
    "        print ('\\n最近' + str(days) + '天股票和策略的累计涨幅:')\n",
    "        print (recent_rtn_line)\n",
    "        print ('\\n过去每一年股票和策略的收益:')\n",
    "        print (year_rtn)\n",
    "        print ('策略年胜率为：%f' % yearly_win_rate)\n",
    "        print ('股票年胜率为：%f' % yearly_win_rates)\n",
    "        print ('\\n过去每一月股票和策略的收益:')\n",
    "        print (month_rtn)\n",
    "        print ('策略月胜率为：%f' % monthly_win_rate)\n",
    "        print ('股票月胜率为：%f' % monthly_win_rates)\n",
    "        print ('\\n过去每一周股票和策略的收益:')\n",
    "        print (week_rtn)\n",
    "        print ('策略周胜率为：%f' % weekly_win_rate)\n",
    "        print ('股票周胜率为：%f' % weekly_win_rates)\n",
    "    return year_rtn, month_rtn, week_rtn, recent_rtn_line"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:55:26.657094Z",
     "start_time": "2019-08-05T14:55:26.623182Z"
    }
   },
   "outputs": [],
   "source": [
    "# 根据每次买入的结果,计算相关指标\n",
    "def trade_indicators(df):\n",
    "    \"\"\"\n",
    "    :param df: 包含日期、仓位和总资产的数据集\n",
    "    :return: 输出账户交易各项指标\n",
    "    \"\"\"\n",
    "    # 计算资金曲线\n",
    "    df['capital'] = (df['capital_rtn'] + 1).cumprod()\n",
    "    # 记录买入或者加仓时的日期和初始资产\n",
    "    df.loc[df['position'] > df['position'].shift(1), 'start_date'] = df['date']\n",
    "    df.loc[df['position'] > df['position'].shift(1), 'start_capital'] = df['capital'].shift(1)\n",
    "    df.loc[df['position'] > df['position'].shift(1), 'start_stock'] = df['close'].shift(1)\n",
    "    # 记录卖出时的日期和当天的资产\n",
    "    df.loc[df['position'] < df['position'].shift(1), 'end_date'] = df['date']\n",
    "    df.loc[df['position'] < df['position'].shift(1), 'end_capital'] = df['capital']\n",
    "    df.loc[df['position'] < df['position'].shift(1), 'end_stock'] = df['close']\n",
    "    # 将买卖当天的信息合并成一个dataframe\n",
    "    df_temp = df[df['start_date'].notnull() | df['end_date'].notnull()]\n",
    "\n",
    "    df_temp['end_date'] = df_temp['end_date'].shift(-1)\n",
    "    df_temp['end_capital'] = df_temp['end_capital'].shift(-1)\n",
    "    df_temp['end_stock'] = df_temp['end_stock'].shift(-1)\n",
    "\n",
    "    # 构建账户交易情况dataframe：'hold_time'持有天数，\n",
    "    #'trade_return'该次交易盈亏,'stock_return'同期股票涨跌幅\n",
    "    trade = df_temp.loc[df_temp['end_date'].notnull(), ['start_date', 'start_capital', 'start_stock',\n",
    "                                                       'end_date', 'end_capital', 'end_stock']]\n",
    "    trade.reset_index(drop=True, inplace=True)\n",
    "    trade['hold_time'] = (trade['end_date'] - trade['start_date']).dt.days\n",
    "    trade['trade_return'] = trade['end_capital'] / trade['start_capital'] - 1\n",
    "    trade['stock_return'] = trade['end_stock'] / trade['start_stock'] - 1\n",
    "\n",
    "    trade_num = len(trade)  # 计算交易次数\n",
    "    max_holdtime = trade['hold_time'].max()  # 计算最长持有天数\n",
    "    average_change = trade['trade_return'].mean()  # 计算每次平均涨幅\n",
    "    max_gain = trade['trade_return'].max()  # 计算单笔最大盈利\n",
    "    max_loss = trade['trade_return'].min()  # 计算单笔最大亏损\n",
    "    total_years = (trade['end_date'].iloc[-1] - trade['start_date'].iloc[0]).days / 365\n",
    "    trade_per_year = trade_num / total_years  # 计算年均买卖次数\n",
    "\n",
    "    # 计算连续盈利亏损的次数\n",
    "    trade.loc[trade['trade_return'] > 0, 'gain'] = 1\n",
    "    trade.loc[trade['trade_return'] < 0, 'gain'] = 0\n",
    "    trade['gain'].fillna(method='ffill', inplace=True)\n",
    "    # 根据gain这一列计算连续盈利亏损的次数\n",
    "    rtn_list = list(trade['gain'])\n",
    "    successive_gain_list = []\n",
    "    num = 1\n",
    "    for i in range(len(rtn_list)):\n",
    "        if i == 0:\n",
    "            successive_gain_list.append(num)\n",
    "        else:\n",
    "            if (rtn_list[i] == rtn_list[i - 1] == 1) or (rtn_list[i] == rtn_list[i - 1] == 0):\n",
    "                num += 1\n",
    "            else:\n",
    "                num = 1\n",
    "            successive_gain_list.append(num)\n",
    "    # 将计算结果赋给新的一列'successive_gain'\n",
    "    trade['successive_gain'] = successive_gain_list\n",
    "    # 分别在盈利和亏损的两个dataframe里按照'successive_gain'的值排序并取最大值\n",
    "    max_successive_gain = trade[trade['gain'] == 1].sort_values(by='successive_gain', \\\n",
    "                        ascending=False)['successive_gain'].iloc[0]\n",
    "    max_successive_loss = trade[trade['gain'] == 0].sort_values(by='successive_gain', \\\n",
    "                        ascending=False)['successive_gain'].iloc[0]\n",
    "\n",
    "    #  输出账户交易各项指标\n",
    "    print ('\\n==============每笔交易收益率及同期股票涨跌幅===============')\n",
    "    print (trade[['start_date', 'end_date', 'trade_return', 'stock_return']])\n",
    "    print ('\\n====================账户交易的各项指标=====================')\n",
    "    print ('交易次数为：%d   最长持有天数为：%d' % (trade_num, max_holdtime))\n",
    "    print ('每次平均涨幅为：%f' % average_change)\n",
    "    print ('单次最大盈利为：%f  单次最大亏损为：%f' % (max_gain, max_loss))\n",
    "    print ('年均买卖次数为：%f' % trade_per_year)\n",
    "    print ('最大连续盈利次数为：%d  最大连续亏损次数为：%d' % (max_successive_gain, max_successive_loss))\n",
    "    return trade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:55:27.877100Z",
     "start_time": "2019-08-05T14:55:27.867130Z"
    }
   },
   "outputs": [],
   "source": [
    "# 计算年化收益率函数\n",
    "def annual_return(date_line, capital_line):\n",
    "    \"\"\"\n",
    "    :param date_line: 日期序列\n",
    "    :param capital_line: 账户价值序列\n",
    "    :return: 输出在回测期间的年化收益率\n",
    "    \"\"\"\n",
    "    # 将数据序列合并成dataframe并按日期排序\n",
    "    df = pd.DataFrame({'date': date_line, 'capital': capital_line})\n",
    "    # 计算年化收益率\n",
    "    annual = (df['capital'].iloc[-1] / df['capital'].iloc[0]) ** (250 / len(df)) - 1\n",
    "    return annual\n",
    "\n",
    "# 计算最大回撤函数\n",
    "def max_drawdown(date_line, capital_line):\n",
    "    df = pd.DataFrame({'date': date_line, 'capital': capital_line})\n",
    "    #计算最大回撤\n",
    "    max_dd = ((df['capital'].cummax()-df['capital']) / df['capital'].cummax()).max()  \n",
    "    return max_dd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-08-05T14:56:11.534984Z",
     "start_time": "2019-08-05T14:56:09.405816Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "最近250天股票和策略的累计涨幅:\n",
      "     trade_date  stock_rtn_line  strategy_rtn_line\n",
      "0           NaN       -0.011601          -0.011601\n",
      "1           NaN       -0.015799          -0.015799\n",
      "2           NaN       -0.017517          -0.017517\n",
      "3           NaN       -0.016797          -0.016797\n",
      "4           NaN       -0.036437          -0.036437\n",
      "5           NaN       -0.057800          -0.057800\n",
      "6           NaN       -0.073361          -0.058998\n",
      "7           NaN       -0.085103          -0.058998\n",
      "8           NaN       -0.058384          -0.058998\n",
      "9           NaN       -0.073579          -0.058998\n",
      "10          NaN       -0.050374          -0.058998\n",
      "11          NaN       -0.048281          -0.058998\n",
      "12          NaN       -0.052383          -0.058998\n",
      "13          NaN       -0.057254          -0.058998\n",
      "14          NaN       -0.079876          -0.058998\n",
      "15          NaN       -0.084138          -0.058998\n",
      "16          NaN       -0.097305          -0.058998\n",
      "17          NaN       -0.086787          -0.058998\n",
      "18          NaN       -0.070184          -0.058998\n",
      "19          NaN       -0.075410          -0.058998\n",
      "20          NaN       -0.072036          -0.058998\n",
      "21          NaN       -0.070552          -0.058998\n",
      "22          NaN       -0.047846          -0.058998\n",
      "23          NaN       -0.049636          -0.058998\n",
      "24          NaN       -0.053437          -0.060793\n",
      "25          NaN       -0.063353          -0.070632\n",
      "26          NaN       -0.067990          -0.075234\n",
      "27          NaN       -0.071534          -0.078750\n",
      "28          NaN       -0.059774          -0.067081\n",
      "29          NaN       -0.078153          -0.085318\n",
      "..          ...             ...                ...\n",
      "220         NaN        0.062487          -0.020388\n",
      "221         NaN        0.060536          -0.022186\n",
      "222         NaN        0.071852          -0.011753\n",
      "223         NaN        0.069272          -0.014132\n",
      "224         NaN        0.100080           0.014273\n",
      "225         NaN        0.100459           0.014623\n",
      "226         NaN        0.088263           0.003378\n",
      "227         NaN        0.082552          -0.001888\n",
      "228         NaN        0.088170           0.003292\n",
      "229         NaN        0.062899          -0.020007\n",
      "230         NaN        0.060200          -0.022496\n",
      "231         NaN        0.058413          -0.024143\n",
      "232         NaN        0.057989          -0.024535\n",
      "233         NaN        0.064560          -0.018476\n",
      "234         NaN        0.068880          -0.022618\n",
      "235         NaN        0.064033          -0.022618\n",
      "236         NaN        0.063415          -0.022618\n",
      "237         NaN        0.053287          -0.022618\n",
      "238         NaN        0.064343          -0.022618\n",
      "239         NaN        0.057000          -0.022618\n",
      "240         NaN        0.059300          -0.022618\n",
      "241         NaN        0.067662          -0.022618\n",
      "242         NaN        0.076392          -0.022618\n",
      "243         NaN        0.078489          -0.022618\n",
      "244         NaN        0.077288          -0.022618\n",
      "245         NaN        0.081772          -0.020406\n",
      "246         NaN        0.072001          -0.029255\n",
      "247         NaN        0.063087          -0.037327\n",
      "248         NaN        0.047426          -0.051509\n",
      "249         NaN        0.027372          -0.069669\n",
      "\n",
      "[250 rows x 3 columns]\n",
      "\n",
      "过去每一年股票和策略的收益:\n",
      "                 ret  capital_rtn\n",
      "trade_date                       \n",
      "2015-12-31  0.055831     0.124580\n",
      "2016-12-31 -0.112818    -0.044563\n",
      "2017-12-31  0.217752     0.122359\n",
      "2018-12-31 -0.253099    -0.190154\n",
      "2019-12-31  0.220894     0.156348\n",
      "策略年胜率为：0.600000\n",
      "股票年胜率为：0.600000\n",
      "\n",
      "过去每一月股票和策略的收益:\n",
      "                 ret  capital_rtn\n",
      "trade_date                       \n",
      "2015-01-31 -0.028105     0.000000\n",
      "2015-02-28  0.040315     0.012284\n",
      "2015-03-31  0.133886     0.133886\n",
      "2015-04-30  0.172459     0.172459\n",
      "2015-05-31  0.019148    -0.033821\n",
      "2015-06-30 -0.075985     0.001307\n",
      "2015-07-31 -0.146724    -0.058485\n",
      "2015-08-31 -0.117947    -0.093596\n",
      "2015-09-30 -0.048593    -0.019277\n",
      "2015-10-31  0.103384     0.032600\n",
      "2015-11-30  0.009147     0.005888\n",
      "2015-12-31  0.046151    -0.006384\n",
      "2016-01-31 -0.210377    -0.093466\n",
      "2016-02-29 -0.023294    -0.066961\n",
      "2016-03-31  0.118375     0.058405\n",
      "2016-04-30 -0.019060    -0.023462\n",
      "2016-05-31  0.004062     0.000000\n",
      "2016-06-30 -0.004935    -0.019616\n",
      "2016-07-31  0.015856     0.025739\n",
      "2016-08-31  0.038660     0.029676\n",
      "2016-09-30 -0.022391    -0.002043\n",
      "2016-10-31  0.025511     0.011251\n",
      "2016-11-30  0.060464     0.060464\n",
      "2016-12-31 -0.064422    -0.013774\n",
      "2017-01-31  0.023528    -0.008205\n",
      "2017-02-28  0.019143     0.019143\n",
      "2017-03-31  0.000937    -0.011229\n",
      "2017-04-30 -0.004714    -0.003333\n",
      "2017-05-31  0.015445     0.027137\n",
      "2017-06-30  0.049792     0.049792\n",
      "2017-07-31  0.019383     0.019383\n",
      "2017-08-31  0.022531    -0.003730\n",
      "2017-09-30  0.003769    -0.003076\n",
      "2017-10-31  0.044369     0.031859\n",
      "2017-11-30 -0.000156     0.006816\n",
      "2017-12-31  0.006179    -0.006541\n",
      "2018-01-31  0.060792     0.060792\n",
      "2018-02-28 -0.058995    -0.016689\n",
      "2018-03-31 -0.031101    -0.056606\n",
      "2018-04-30 -0.036327     0.000000\n",
      "2018-05-31  0.012109    -0.015104\n",
      "2018-06-30 -0.076635     0.000000\n",
      "2018-07-31  0.001903     0.021155\n",
      "2018-08-31 -0.052068    -0.059435\n",
      "2018-09-30  0.031300     0.000281\n",
      "2018-10-31 -0.082891    -0.091744\n",
      "2018-11-30  0.005980    -0.031400\n",
      "2018-12-31 -0.051071    -0.011351\n",
      "2019-01-31  0.063433     0.035299\n",
      "2019-02-28  0.146094     0.146094\n",
      "2019-03-31  0.055315     0.019183\n",
      "2019-04-30  0.010555    -0.022515\n",
      "2019-05-31 -0.072425     0.000000\n",
      "2019-06-30  0.053942     0.036623\n",
      "2019-07-31  0.002552    -0.015340\n",
      "2019-08-31 -0.041632    -0.041632\n",
      "策略月胜率为：0.470588\n",
      "股票月胜率为：0.607143\n",
      "\n",
      "过去每一周股票和策略的收益:\n",
      "                 ret  capital_rtn\n",
      "trade_date                       \n",
      "2015-01-11  0.003684     0.000000\n",
      "2015-01-18  0.024930     0.000000\n",
      "2015-01-25 -0.017444     0.000000\n",
      "2015-02-01 -0.038452     0.000000\n",
      "2015-02-08 -0.035514     0.000000\n",
      "2015-02-15  0.047521     0.000000\n",
      "2015-02-22  0.015129     0.000000\n",
      "2015-03-01  0.014343     0.012284\n",
      "2015-03-08 -0.026401    -0.026401\n",
      "2015-03-15  0.039998     0.039998\n",
      "2015-03-22  0.075993     0.075993\n",
      "2015-03-29  0.020326     0.020326\n",
      "2015-04-05  0.050065     0.050065\n",
      "2015-04-12  0.041691     0.041691\n",
      "2015-04-19  0.057941     0.057941\n",
      "2015-04-26  0.023172     0.023172\n",
      "2015-05-03  0.010046     0.010046\n",
      "2015-05-10 -0.040313    -0.040313\n",
      "2015-05-17  0.012958    -0.010495\n",
      "2015-05-24  0.072306     0.040669\n",
      "2015-05-31 -0.022318    -0.022318\n",
      "2015-06-07  0.080508     0.080508\n",
      "2015-06-14  0.019991     0.019991\n",
      "2015-06-21 -0.130844    -0.091462\n",
      "2015-06-28 -0.064881     0.000000\n",
      "2015-07-05 -0.103841     0.000000\n",
      "2015-07-12  0.056780     0.000000\n",
      "2015-07-19  0.010943     0.000000\n",
      "2015-07-26  0.005970     0.004145\n",
      "2015-08-02 -0.086101    -0.062371\n",
      "...              ...          ...\n",
      "2019-01-20  0.023716     0.024480\n",
      "2019-01-27  0.005144     0.005144\n",
      "2019-02-03  0.019760     0.019760\n",
      "2019-02-10  0.000000     0.000000\n",
      "2019-02-17  0.028118     0.028118\n",
      "2019-02-24  0.054337     0.054337\n",
      "2019-03-03  0.065224     0.065224\n",
      "2019-03-10 -0.024571    -0.024571\n",
      "2019-03-17  0.023903     0.023903\n",
      "2019-03-24  0.023711     0.023711\n",
      "2019-03-31  0.010052    -0.024530\n",
      "2019-04-07  0.049037     0.019041\n",
      "2019-04-14 -0.018122    -0.018122\n",
      "2019-04-21  0.033092     0.033092\n",
      "2019-04-28 -0.056140    -0.056140\n",
      "2019-05-05  0.006154     0.001877\n",
      "2019-05-12 -0.046703     0.000000\n",
      "2019-05-19 -0.021897     0.000000\n",
      "2019-05-26 -0.015031     0.000000\n",
      "2019-06-02  0.009982     0.000000\n",
      "2019-06-09 -0.017937     0.000000\n",
      "2019-06-16  0.025304    -0.009634\n",
      "2019-06-23  0.048992     0.048992\n",
      "2019-06-30 -0.002179    -0.002179\n",
      "2019-07-07  0.017674     0.017674\n",
      "2019-07-14 -0.021697    -0.021697\n",
      "2019-07-21 -0.000204    -0.004219\n",
      "2019-07-28  0.013291     0.000000\n",
      "2019-08-04 -0.028803    -0.029560\n",
      "2019-08-11 -0.019146    -0.019146\n",
      "\n",
      "[240 rows x 2 columns]\n",
      "策略周胜率为：0.547771\n",
      "股票周胜率为：0.565957\n",
      "\n",
      "==============每笔交易收益率及同期股票涨跌幅===============\n",
      "   start_date   end_date  trade_return  stock_return\n",
      "0  2015-02-25 2015-05-11      0.298216      0.331659\n",
      "1  2015-05-15 2015-05-20      0.012980      0.011517\n",
      "2  2015-05-22 2015-06-19     -0.009974     -0.042125\n",
      "3  2015-07-23 2015-07-30     -0.058485     -0.082207\n",
      "4  2015-08-14 2015-08-21     -0.093596     -0.119232\n",
      "5  2015-09-23 2015-09-28     -0.019277     -0.028834\n",
      "6  2015-10-13 2015-11-30      0.038680      0.034434\n",
      "7  2015-12-18 2016-01-05     -0.099254     -0.073780\n",
      "8  2016-02-22 2016-03-02     -0.048657     -0.000083\n",
      "9  2016-03-08 2016-04-22      0.013686      0.022565\n",
      "10 2016-06-02 2016-06-17     -0.019616     -0.015880\n",
      "11 2016-07-04 2016-07-29      0.025739      0.015766\n",
      "12 2016-08-12 2016-09-05      0.027573      0.026697\n",
      "13 2016-10-13 2016-12-12      0.057624      0.033082\n",
      "14 2017-01-10 2017-01-17     -0.016665     -0.011161\n",
      "15 2017-01-23 2017-03-09      0.024961      0.021478\n",
      "16 2017-03-17 2017-04-20     -0.011688     -0.005733\n",
      "17 2017-05-22 2017-08-14      0.073744      0.085443\n",
      "18 2017-08-23 2017-09-26      0.016735      0.018251\n",
      "19 2017-10-10 2017-11-30      0.038892      0.031913\n",
      "20 2017-12-25 2018-02-05      0.036265      0.054148\n",
      "21 2018-03-12 2018-03-23     -0.056606     -0.049632\n",
      "22 2018-05-10 2018-05-29     -0.015104     -0.017462\n",
      "23 2018-07-19 2018-08-03     -0.022676     -0.033818\n",
      "24 2018-08-29 2018-09-06     -0.031348     -0.040377\n",
      "25 2018-09-26 2018-10-12     -0.078269     -0.061861\n",
      "26 2018-11-06 2018-11-27     -0.031400     -0.038492\n",
      "27 2018-12-06 2018-12-12     -0.011351     -0.025029\n",
      "28 2019-01-14 2019-03-29      0.209313      0.251250\n",
      "29 2019-04-02 2019-04-29     -0.022515     -0.018519\n",
      "30 2019-06-14 2019-07-15      0.027700      0.037661\n",
      "\n",
      "====================账户交易的各项指标=====================\n",
      "交易次数为：31   最长持有天数为：84\n",
      "每次平均涨幅为：0.008246\n",
      "单次最大盈利为：0.298216  单次最大亏损为：-0.099254\n",
      "年均买卖次数为：7.067458\n",
      "最大连续盈利次数为：4  最大连续亏损次数为：7\n",
      "\n",
      "股票的年化收益为：0.002087405976016754\n",
      "策略的年化收益为：0.02754201589606975\n",
      "\n",
      "股票最大回撤: 0.46696135102286235\n",
      "策略最大回撤: 0.3444860077492887\n"
     ]
    }
   ],
   "source": [
    "pd.options.mode.chained_assignment = None\n",
    "# =====读取数据\n",
    "df0=get_daily_data('沪深300',start='20150101')\n",
    "# =====根据策略,计算仓位,资金曲线等\n",
    "# 计算买卖信号\n",
    "stock_data=strategy_ma(df0, short=5, long=20)\n",
    "# 计算策略每天涨幅\n",
    "return_data = position(stock_data)\n",
    "# 计算资金曲线\n",
    "return_data['capital'] = (return_data['capital_rtn'] + 1).cumprod()\n",
    "# =====根据策略结果,计算评价指标\n",
    "# 计算最近250天的股票,策略累计涨跌幅.以及每年（月，周）股票和策略收益\n",
    "period_return(return_data, days=250, if_print=True)\n",
    "# 根据每次买卖的结果,计算相关指标\n",
    "trade_indicators(stock_data)\n",
    "# =====根据资金曲线,计算相关评价指标\n",
    "date_line = list(return_data['date'])\n",
    "capital_line = list(return_data['capital'])\n",
    "stock_line = list(return_data['close'])\n",
    "print (f'\\n股票的年化收益为：{annual_return(date_line, stock_line)}')\n",
    "print (f'策略的年化收益为：{annual_return(date_line, capital_line)}')\n",
    "print (f'\\n股票最大回撤: {max_drawdown(date_line, stock_line)}')\n",
    "print (f'策略最大回撤: {max_drawdown(date_line, capital_line)}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
